package antani.client.pages;

import antani.client.GWTClient;
import antani.client.widgets.AlbumItem;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.Panel;

public class AlbumsPage extends Page {

	public final static String MODE_ALL = "all";
	public final static String MODE_RANDOM = "random";
	public final static String MODE_TIMELINE = "timeline";
	public static final String MODE_ARTIST = "artist";

	Panel albumPanel;

	public String mode = MODE_ALL;
	public String filter = null;

	public AlbumsPage(Panel albumPanel) {
		this.albumPanel = albumPanel;
	}

	public void showAlbums() {

		String url = "/query?type=album";
		if (mode.equals(MODE_ARTIST))
			url += "&" + filter;
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url + getUniqueParam());
		try {
			builder.sendRequest("", new RequestCallback() {

				@Override
				public void onResponseReceived(Request request, Response response) {
					String msg = response.getText();

					String[] albums = msg.split("\\n");

					for (int i = 0; i < albums.length; i++) {
						String line = albums[i];

						// parse line
						String[] tokens = line.split(";");
						if (tokens.length < 3) {
							continue;
						}
						String id = tokens[0];
						String album = tokens[1];
						String artist = tokens[2];
						albumPanel.add(new AlbumItem(id, album, artist));
					}
				}

				@Override
				public void onError(Request request, Throwable exception) {
					// TODO Auto-generated method stub

				}
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void activate() {
		albumPanel.setVisible(true);
		showAlbums();
	}

	@Override
	public void deactivate() {
		albumPanel.clear();
		albumPanel.setVisible(false);
	}

	public void showAlbumPopup(final String id) {
		GWTClient.playerPage.playAlbum(id);
	}
}
